<template>
  <div>
    <el-button type="primary" @click="openDialog">新建任务</el-button>
    <!-- 使用 v-model 绑定 isVisible -->
    <CreateTaskDialog :isShow="isVisible" :loadingInstance="instance" @close="closeDialog" @update:records="getAllRecordsFromDB"></CreateTaskDialog>
  </div>
  <el-table :data="task_record_list" style="width: 100%" v-loading="loading">
    <el-table-column prop="task_id" label="任务ID" width="200px"></el-table-column>
    <el-table-column prop="status" label="状态" width="auto"></el-table-column>
    <el-table-column prop="task_name" label="任务名称" width="auto"></el-table-column>
    <el-table-column prop="start_time" label="开始时间" width="150px"></el-table-column>
    <el-table-column prop="end_time" label="结束时间" width="150px"></el-table-column>
    <el-table-column label="进度" width="400px">
      <template #default="scope">
        <progress-vue :progress="scope.row.progress" :bar_status="scope.row.bar_status" :loading="scope.row.loading" :durations="scope.row.duration"></progress-vue>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="300px">
      <template #default="scope">
        <el-button-group class="button-group">
          <el-button v-if="scope.row.status === 'finished'" type="danger" :loading="scope.row.loading" @click="deleteRecord(scope.row)">删除</el-button>
          <el-button v-else-if="scope.row.status === 'crawling' || scope.row.status === 'pending' || scope.row.status === 'initializing'" type="warning" :loading="scope.row.loading" @click="cancelCrawling(scope.row)">取消</el-button>
          <el-button v-else-if="scope.row.status === 'failed'" type="danger" @click="retryCrawling(scope.row)" :loading="scope.row.loading">重试</el-button>
          <el-button v-if="scope.row.status === 'failed'" type="danger" @click="deleteRecord(scope.row)" :loading="scope.row.loading">删除</el-button>
        </el-button-group>
      </template>
    </el-table-column>
  </el-table>

</template>

<script setup>
import CreateTaskDialog from "@/components/Dialog/CreateTaskDialog.vue";
import {onMounted, ref, watch,reactive} from "vue";
import ProgressVue from "@/components/Progress/ProgressVue.vue";
import {getAllTasksRecord, getProgress, cancelTaskByJobId, deleteTaskRecordByJobId} from "@/api/utils.js";
import { ElMessage } from "element-plus";
const isVisible = ref(false);
const openDialog = () => {
  isVisible.value = true;
};
const loading = ref(false)
const closeDialog = (val) => {
  isVisible.value = val
}
const task_record_list = ref([])
let intervalId;
const fetchProgress = async () => {
  console.log("更新进度!")
  try {
    let allTasksFinished = true;
    for (const item of task_record_list.value) {
      if (item.status != 'finished' && item.status != 'failed') {
        allTasksFinished = false;
        // console.log(item.task_id)
        // console.log(item.status)
        const response = await getProgress(item.task_id)
        const data = response.data
        item.status = data.status
        item.progress = Math.floor((data.completed_nums / (data.total_nums - data.failed_nums)) * 100)
      }else if(item.status === 'failed'){
        const response = await getProgress(item.task_id)
        const data = response.data
        item.progress =  Math.floor((data.completed_nums / (data.total_nums - data.failed_nums)) * 100)
        item.bar_status = 'exception'
        item.duration = 0
      }else{
        item.progress = 100;
        item.duration = 0; // Set duration to 0 when status is 'finished'
      }
    }
    if (allTasksFinished) {
      clearInterval(intervalId); // Cancel the timer if all tasks are finished
    }
  } catch (error) {
    console.error('Failed to fetch progress', error)
  }
}
// 这里得监听task_record_list,而不是task_record_list.value
watch(task_record_list, async () => {
  fetchProgress()
  // 在新建任务之后也要加入定时器，
  // 先判断intervalId定时器是否存在，不存在则新建
  if(!intervalId){
    intervalId = setInterval(fetchProgress, 6000);
  }
},)
const getAllRecordsFromDB =  async () =>{
  // 记录加载中
  loading.value = true
  console.log("记录加载中")
  // console.log("更新记录被调用了!")

  let result =await getAllTasksRecord();
  console.log(result)
  let data = result["data"]
  // 添加loading属性,初始化为false
  if (Array.isArray(data)) {
    data = data.map(item => ({...item, loading:false}))
  }
  console.log(data)
  // console.log(`自定义修改后的data:${data}`)
  task_record_list.value = data;
  // 记录加载完成
  loading.value = false
}
const deleteRecord = async (row)=>{
  row.loading = true
  //对于已完成的任务删除数据库中的记录
  const taskId = row.task_id
  try{
    const res = await deleteTaskRecordByJobId(taskId)
    if(res.status === 200){
      await getAllRecordsFromDB()
      row.loading = false
      ElMessage.success(res.data)
    }else{
      ElMessage.error(res.data)
    }
  }catch (error){
    console.log(error)
    ElMessage.error(error)

  }

}
const cancelCrawling = async (row) => {
  row.loading = true
  // 取消scrapyd中的任务同时从数据库删除记录
  const taskId = row.task_id
  try{
    const response = await cancelTaskByJobId(taskId)
    if(response.status === 200){
      const res = await deleteTaskRecordByJobId(taskId)
      if(res.status === 200){
        await getAllRecordsFromDB()
        row.loading = true
        ElMessage.success(res.data)
      }else{
        ElMessage.error(res.data)
      }
    }else {
      ElMessage.error(response.data)
    }
  }catch (error){
    ElMessage.error(error)
  }
}
const retryCrawling = () => {
   // 删除数据库中的记录同时发起心的任务请求
  // 要先获取原有的信息，如是请求文件和请求函数
}

onMounted(async () => {
  //这里要加入await，然后容易造成数据还没有返回来就执行fetchPro没有数据，然后导致没有数据，使得下一次fetchProgress才能正确显示
  await getAllRecordsFromDB()
  console.log(task_record_list.value)
  // 先请求一次
  fetchProgress()
  intervalId = setInterval(fetchProgress, 6000);



})



</script>

<style scoped>
.task-item {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
}
.task-item span{
  margin: 10px;
}
.button-group .el-button{
  margin-right: 10px;
}
</style>
